import { ref, watch, nextTick, computed } from 'vue'
export default function (singerlist, scrollref) {
  const wrapref = ref(null)
  // 记录每个子元素高度
  const heightarr = [0]
  // 记录当前滚动到第几个
  const currentindex = ref(0)
  // 顶部固定的标题到当前块底部的距离
  let hei = 0
  // 当数据改变并且渲染完毕，才能遍历子节点
  watch(singerlist, async () => {
    await nextTick()
    for (let i = 0; i < wrapref.value.children.length; i++) {
      hei += wrapref.value.children[i].clientHeight
      heightarr.push(hei)
    }
  })
  // 监听滚动事件
  const onScroll = (pos) => {
    heightarr.forEach((item, index) => {
      if (-pos.y >= item) {
        return (currentindex.value = index)
      }
    })
  }
  // 计算当前顶部应该显示的标题
  const fixedTitle = computed(() => {
    const title =
      singerlist.value.length > 0
        ? singerlist.value[currentindex.value].title
        : ''
    return title
  })

  // 右侧导航栏逻辑
  // 计算标题
  const shortcutList = computed(() => {
    return singerlist.value.map((item) => item.title)
  })
  // 利用事件委托监听事件
  // 监听触摸事件
  const touch = {}
  const onStart = (e) => {
    if (!e.target.dataset.index) {
      return
    }
    touch.y = e.touches[0].pageY
    const index = Math.max(
      0,
      Math.min(
        parseInt(e.target.dataset.index),
        wrapref.value.children.length - 1
      )
    )
    touch.index = index
    scrollref.value.scroll.scrollToElement(wrapref.value.children[index], 200)
  }
  // 监听移动
  const onMove = (e) => {
    const dis = e.touches[0].pageY - touch.y
    const disindex = (dis / 18) | 0
    currentindex.value = Math.max(
      0,
      Math.min(touch.index + disindex, wrapref.value.children.length - 1)
    )
  }
  return {
    onScroll,
    wrapref,
    currentindex,
    fixedTitle,
    shortcutList,
    onStart,
    onMove
  }
}
